/**
 * @author xuezhenan
 * 企业通讯录插件，
 * 初始化：
 * $().vitobooks({
 * 		title: "三维云办公",
		width: 500,
		height: 470,
		userType: "user", //user,dept,role
		checkType: "checkbox", //checkbox,radio
		closed: false, //初始化后是否立即打开
		checks: [], //初始勾选节点,需要开启backfill
		backfill: false, //是否回填数据
		url: null,//可自定义请求数据接口
		data: null,//可直接加载的数据
		beforeSave: null,
		beforeCheck: null,
		onSave: null,
		onCheck: null,	
 * });
 * 方法：
 * $().vitobooks('open|close|clear|cancel|save|alert|options');
 */
define(function(require, exports, module){
	// require("resource/js/component/jquery.ztree.core-3.5.js");
	// require("resource/js/component/ztree.check.js");
	// require("resource/js/component/ztreeStyle.css")
	require("resource/js/component/vitoBooks/vitobooks.css");
	require("resource/css/oaTreeStyle.css");
	require("resource/font-awesome-4.7.0/css/font-awesome.min.css");
	require("resource/js/component/vitoBooks/vitobooks.css");
	var AJAX = require("resource/js/component/ajax.js");

	function isUndefined(i) {
		return "undefined" == typeof i;
	}

	function isString(i) {
		return typeof i == "string";
	}

	function isExist(array, key, value) {
		var is = false;
		if (array && array.length > 0) {
			$.each(array, function(i, item) {
				item[key] && item[key] == value && (is = true);
			});
		}
		return is;
	}

	function splice(array, data) {
		var index = array.indexOf(data);
		index > -1 && array.splice(index, 1);
	}

	function push(array, data) {
		var index = array.indexOf(data);
		index > -1 ? array.splice(index, 1, data) : array.push(data);
	}

	var typeTitle = {
		"USER": "请选择员工",
		"DEPT": "请选择部门",
		"ROLE": "请选择职务",
		"default": "请选择"
	};
	var dataUrl = {
		'USER': '/base/authoriza/user/getUserListByDeptId.htm',
		'DEPT': '/base/authoriza/dept/queryDeptTreeByRootDept.htm',
		'ROLE': '/oa/act/approver/queryRoleByDept.htm'
	}

	var books = function(ele, opt) {
		this.defaults = {
			title : "三维云办公",
			width:500, 
			height:470,	
			nodeType : null, //树节点类型  USER  DEPT  ROLE
			defaultUrl: null,//user,dept,role url类型 如果没有类型则需要url
			checkType : "checkbox",//checkbox,radio
			closed : false,//初始化后是否立即打开
			checks:[],//初始勾选节点,需要开启backfill
			backfill : false,//是否回填数据
			url : null,
			data: null,
			beforeSave:null,
			beforeCheck:null,
			onSave : null,
			onCheck : null,
			seachFlag: true, //是否显示搜索
			ztreeidKey: "id", //字段  idKey
			ztreepIdKey: "pid", //字段 pIdKey
			ztreetitle: "name", //字段名称 title
			ztreename: "name", //字段名称 name
		};
		this.$element = $(ele);
		this.options = $.extend({},this.defaults,opt);
		var num = Math.ceil(Math.random()*100);
		this.dlgId = "vitoBooks_dlg_"+num;
		this.treeId = "vitoBooks_tree_"+num;
		this.treeSearchInput = "treeSearchInput_" + num;
		this.treeSearchBtn = "treeSearch_" + num;
		var searchHtml = '';
		if (this.options.seachFlag) {
			searchHtml = '<div class="tree-search-block"><input type="text" class="tree-search-input" id="'+this.treeSearchInput+'"/><span class="tree-search-icon" id="'+this.treeSearchBtn+'">&nbsp;</span></div>';
		}
		this.template = '<div style="margin: 0;padding: 0;height:100%;width:100%;position: relative;">'
			+'<div class="vitobooks-alert"></div>'
			+'<div class="vitobooks-west">'
				+'<div class="vitobooks-header">请选择</div>'
				+ searchHtml 
				+'<ul id="'+this.treeId+'" class="ztree treeselect" style="overflow:auto;height:100%;"></ul>'	 
			+'</div>'
			+'<div class="vitobooks-east">'
				+'<div class="vitobooks-header">已选列表</div>'
				+'<ul class="checkedList" style="overflow:auto;height:100%;padding:0;"></ul>'	
			+'</div></div>';
		
		this.checks=[];//已被保存的勾选节点（再次打开回填需要）
		this.tempChecks=[];//未保存的勾选节点
		this.treeObj = null;
		this.init();
	}
	books.prototype = {
		constructor: books,	
		init : function(){
			var opt = this.options;
			if(opt.defaultUrl){
				this.options.url = dataUrl[opt.defaultUrl.toUpperCase()]
			}
			this.loadDlg();
			!opt.closed && this.open();
		},
		loadTree : function(){
			var books = this;
			var opt = this.options;
			var id = this.treeId;
			var tree = null;
			var checkType= opt.checkType;
			var nodeType = "";
			if (opt.nodeType) {
				nodeType = opt.nodeType.toUpperCase();
			}
			var setting = {
					check: {
						enable: true,
						autoCheckTrigger: true,
						chkboxType: {
							"Y": "ps",
							"N": "ps"
						},
						radioType : "all",
						chkStyle: checkType,
					},
					view: {
						showIcon: false,
						showLine: false,
						showTitle: true,
						addDiyDom: function(treeId, treeNode) {
							var aObj = $('#'+books.treeId).find("#" + treeNode.tId + "_a");
							var swich = $('#'+books.treeId).find("#" + treeNode.tId + "_switch");
							if(checkType == "radio" && treeNode.type != nodeType){
								$('#'+books.treeId).find("#" + treeNode.tId + "_check").remove();
							} 
							var check = $('#'+books.treeId).find("#" + treeNode.tId + "_check").insertAfter(swich);
							if (treeNode.type == "DEPT") {
								if (treeNode.parentTId == null) {
									$('<i class="fa fa-home" aria-hidden="true"></i>').prependTo(aObj)
								} else {
									$('<i class="fa fa-map-signs" aria-hidden="true"></i>').prependTo(aObj)
								}
							} else if(treeNode.type == "USER"){
								$('<i class="fa fa-user" aria-hidden="true"></i>').prependTo(aObj);
							 }else{
								$('<i class="fa fa-tag" style="color:#8BC34A;" aria-hidden="true"></i>').prependTo(aObj);
							}
						},
						fontCss: setFontCss_ztree
					},
					callback: {
						beforeCheck :function(treeId,node){
							return books.beforeCheck.apply(books,[node]);
						},
						onCheck: function(eventId,treeId,node){
							var treeObj =  $.fn.zTree.getZTreeObj(treeId);
								var isChecked = node.getCheckStatus().checked;
								var isRadio = treeObj.setting.check.chkStyle == "radio"?true:false;
								var $checksWarp = $('#'+books.dlgId).find(".checkedList");
								if(isChecked){
									if(node.type == nodeType){
										if(isRadio){
											$checksWarp.empty();
											books.tempChecks=[];
										}
										$('<li id='+node.tId+'><i class="fa fa-user" aria-hidden="true"></i><span class="user-info" >'+node[opt.ztreename]+'</span><span class="tree_Close"></span></li>')
										.appendTo($checksWarp)
										.data('node',node)	
										.bind('click',function(){
											var node = $(this).data('node');
											treeObj.checkNode(node, false, true, true);
										});
										books.onCheck.apply(books,[node,isChecked]);
									}
								} else {
									if (node.type == nodeType) {
										$checksWarp.find("li#" + node.tId).remove();
										books.onCheck.apply(books,[node,isChecked]);
									}
								}
						}
					},
					data: {
						simpleData: {
							enable: true,
							idKey: opt.ztreeidKey,
							pIdKey: opt.ztreepIdKey,
							rootPId: 0
						},
						key: {
							title: opt.ztreetitle,
							name: opt.ztreename,
						}
					},
					async : {
						url:null
					}
				};
			using(["ztreebox"],function(){
				//加载tree
				if(opt.url && $.trim(opt.url)!=''){
					AJAX.init().sync().success(function(code,msg,data){
						if(code==0){
							tree = $.fn.zTree.init($('#'+id), setting, data);
							
						}
					}).post(BASEPATH+opt.url,opt.args);
				}else if(opt.data && opt.data.length > 0){
					tree = $.fn.zTree.init($('#'+id), setting, opt.data);
				}else{
					tree = $.fn.zTree.init($('#'+id), setting,[]);
				}
				
				var firstNode = tree.getNodes()[0];
				tree.expandNode(firstNode,true,false,true);
				
				//数据回填操作
				if(opt.backfill){
					var checks1 = opt.checks||[];//用户初始化欲勾选
					var checks2 = books.checks||[];//已勾选
					if (checks2 == undefined || checks2.length == 0) {
						$.each(checks1,function(i,item){
							var node = tree.getNodeByParam(opt.ztreeidKey,item);
							node && tree.checkNode(node,true,false ,true);
						});
					}
					$.each(checks2,function(i,item){
						var parentNode = item.getParentNode();
						var node = tree.getNodeByParam(opt.ztreeidKey,item.id,parentNode);
						item && tree.checkNode(node,true,false ,true);
					});
				}
				books.treeObj = tree;
			})
			
		},
		loadDlg : function(){
			var books = this;
			var type = ""
			if (books.options.nodeType) {
				type = books.options.nodeType.toUpperCase();
			}
			var dlgId = books.dlgId;
			var treeId = books.treeId;
			var template = books.template;
			var treeSearchBtn = books.treeSearchBtn;
			var treeSearchInput = books.treeSearchInput;
			using('dialog',function(){
				$('<div id='+dlgId+'></div>').after(books.$element).dialog({
					title:books.options.title,
					closed: true,
					modal:true,
					width:books.options.width, 
					height:books.options.height,	
					resizable:false,
					draggable:false,
					content:template,
					onBeforeOpen:function(){
						$('#'+dlgId).find('.vitobooks-west .vitobooks-header').text(typeTitle[type] || typeTitle['default']);
						$('#'+dlgId).find('.vitobooks-east .vitobooks-header').text("已选列表");
						books.loadTree();
						//点击搜索
						$('#'+dlgId).on('click', '#' + treeSearchBtn, function() {
							search_ztree(treeId, treeSearchInput, books.options);
						});
						//监听回车
						$('#'+dlgId).on('keypress', '#' + treeSearchInput, function(event) {
							if (event.keyCode == "13") {
								event.preventDefault(); 
								search_ztree(treeId, treeSearchInput, books.options);
							}
						});
					},
					onClose: function() {
						$('#'+dlgId).find('.checkedList').empty();
					},	
					buttons:[
						{
							text:'确定',
							iconCls:'icon-ok',
							accessKey:{akey:18,mkey:83},
							handler:function(){
								books.save.apply(books,[]);
							}
						}, {
							text: '取消',
							addClass: 'l-btn-red',
							iconCls: 'icon-not',
							accessKey: {
								akey: 18,
								mkey: 67
							},
							handler: function() {
								books.cancel.apply(books,[]);
							}
						}, {
							text: '清空',
							iconCls: 'icon-not',
							handler: function() {
								books.clear.apply(books,[]);
							}
						}]
				});
			});
		},
		beforeCheck : function(node){
			var books = this;
			//防止一个用户处于多部门情况
			if(!node.checked && isExist(books.tempChecks,books.options.ztreeidKey,node[books.options.ztreeidKey])){
				books.alert('该对象已被选择');
				return false;
			}
			var beforeCheck = this.options.beforeCheck;
			return beforeCheck && $.isFunction(beforeCheck) && beforeCheck.apply(this,[node]);
		},
		onCheck : function(node,checked){
			var onCheck = this.options.onCheck;
			checked? push(this.tempChecks,node) : splice(this.tempChecks,node);
			onCheck && $.isFunction(onCheck) && onCheck.apply(this,[node]);
		},
		getCheckedNodes: function(){
			var books = this;
			var nodes = this.tempChecks;
			var a=[];
			$.each(nodes,function(i,item){
				var user = {
					'id':item[books.options.ztreeidKey], 
					'name':item[books.options.ztreename], 
					'type':item.type,
					'parentId':item[books.options.ztreepIdKey],
				}
				a.push(user);
			});
			return a;
		},
		open : function(){
			var id =this.dlgId;
			this.tempChecks = [];
			using('dialog',function(){
				$('#'+id).dialog('open').dialog('resize',{top:(window.innerHeight-$('#'+id).dialog("options").height)/2});
			});
		},
		close : function(){
			var id =this.dlgId;
			this.tempChecks = [];
			var onClose = this.options.onClose;
			onClose && $.isFunction(onClose) && onClose.apply(this,[]);
			using('dialog',function(){
				$('#'+id).dialog('close');
			});
		},
		save : function(){
			var beforeSave = this.options.beforeSave;
			var onSave = this.options.onSave;
			var checks = this.getCheckedNodes();
			if($.isFunction(beforeSave) && beforeSave.apply(this,[checks])==false){
				return;
			}
			this.checks = this.tempChecks;
			onSave && $.isFunction(onSave) && onSave.apply(this,[checks]);
			this.close();
		},
		otherSave: function(){
			this.checks = this.tempChecks;
			this.close();
		},
		clear : function(){
			var treeObj = this.treeObj;
			var checks = this.tempChecks.splice(0);
			$.each(checks,function(i,item){
				treeObj.checkNode(item,false,true,true);
			})
		},
		cancel : function(){
			this.close();
		},
		alert : function(msg){
			$('#'+this.dlgId).find('.vitobooks-alert')
			.text(msg)
			.css('left',($('#'+this.dlgId).innerWidth()-$('#'+this.dlgId).find('.vitobooks-alert').innerWidth())/2)
			.fadeIn()
			.delay(1500)
			.fadeOut();
		},
		options : function(){
			return this.options;
		}
	};
	
	/***************搜索开始***************/
	/**
	 * 搜索树
	 */
	function search_ztree(treeId, searchConditionId, ztreeOpt){
		searchByFlag_ztree(treeId, searchConditionId, "", ztreeOpt);
	}
	var highlightNodes = new Array();
	/**
	 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
	 */
	function searchByFlag_ztree(treeId, searchConditionId, flag, ztreeOpt) {
	    //1.搜索条件
	    var searchCondition = $('#' + searchConditionId).val().trim();
	    //2.得到模糊匹配搜索条件的节点数组集合
	    var treeObj = $.fn.zTree.getZTreeObj(treeId);
	    updateNodes(treeObj,highlightNodes,false);
	    if (searchCondition != "") {
	        highlightNodes = treeObj.getNodesByParamFuzzy(ztreeOpt.ztreename, searchCondition, null);
	    }
	    //3.高亮显示并展示【指定节点s】
	    highlightAndExpand_ztree(treeId, highlightNodes, flag);
	}
	function updateNodes(treeObj,highlightNodes,highlightFlag) {
		for( var i=0, l=highlightNodes.length; i<l; i++) {
			highlightNodes[i].highlight=highlightFlag;
			treeObj.updateNode(highlightNodes[i]);
		}
	}
	/**
	 * 高亮显示并展示
	 */
	function highlightAndExpand_ztree(treeId, highlightNodes, flag) {
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		treeObj.expandAll(false);
		treeObj.refresh();
		if (highlightNodes != null) {
			for (var i = 0; i < highlightNodes.length; i++) {
				if (flag != null && flag != "") {
					if (highlightNodes[i].flag == flag) {
						//高亮显示节点，并展开
						highlightNodes[i].highlight = true;
						treeObj.updateNode(highlightNodes[i]);
						//高亮显示节点的父节点的父节点....直到根节点，并展示
						var parentNode = highlightNodes[i].getParentNode();
						var parentNodes = getParentNodes_ztree(treeId, parentNode);
	                    treeObj.expandNode(parentNodes, true, false, true);
	                    treeObj.expandNode(parentNode, true, false, true);
					}
				} else {
					//高亮显示节点，并展开
					highlightNodes[i].highlight = true;
	                treeObj.updateNode(highlightNodes[i]);
	                //高亮显示节点的父节点的父节点....直到根节点，并展示
	                var parentNode = highlightNodes[i].getParentNode();
	                var parentNodes = getParentNodes_ztree(treeId, parentNode);
	                treeObj.expandNode(parentNodes, true, false, true);
	                treeObj.expandNode(parentNode, true, false, true);
				}
			}
		}
	}
	
	/**
	 * 递归得到指定节点的父节点的父节点....直到根节点
	 */
	function getParentNodes_ztree(treeId, node) {
	    if (node != null) {
	        var treeObj = $.fn.zTree.getZTreeObj(treeId);
	        var parentNode = node.getParentNode();
	        return getParentNodes_ztree(treeId, parentNode);
	    } else {
	        return node;
	    }
	}
	/**
	 * 设置树节点字体样式
	 */
	function setFontCss_ztree(treeId, treeNode) {
	    if (treeNode.id == 0) {
	        //根节点
	        return {color: "#333", "font-weight": "500"};
	    } else if (treeNode.isParent == false) {
	        //叶子节点
	        return (!!treeNode.highlight) ? {color: "rgb(57, 141, 238)", "font-weight": "bold"} : {
	            color: "#660099",
	            "font-weight": "normal"
	        };
	    } else {
	        //父节点
	        return (!!treeNode.highlight) ? {color: "rgb(57, 141, 238)", "font-weight": "bold"} : {
	            color: "#333",
	            "font-weight": "normal"
	        };
	    }
	}
	/***************搜索结束***************/
	
	$.fn.vitoBooks = function(conf){
		var r,a=Array.prototype.slice.call(arguments,1);
		return this.each(function(){
			var method,book = $(this).data('vitobooks');
			if(!book){
				$(this).data('vitobooks',book = new books(this,conf));
			}
			isString(conf) && $.isFunction(method = book[conf]) && (r = method.apply(book, a))
		}), isUndefined(r) ? this : r
	};
});